{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20335d29",
   "metadata": {},
   "outputs": [],
   "source": [
    "## [删除链表的倒数第N个节点](https://leetcode.cn/problems/remove-nth-node-from-end-of-list/)\n",
    "# Definition for singly-linked list.\n",
    "\n",
    "# 法一：直接遍历\n",
    "class ListNode:\n",
    "    def __init__(self, val=0, next=None):\n",
    "        self.val = val\n",
    "        self.next = next\n",
    "\n",
    "class Solution:\n",
    "    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n",
    "        dummy = ListNode(0)\n",
    "        dummy.next = head\n",
    "        count = 0\n",
    "        current = head\n",
    "        while current:\n",
    "            count += 1\n",
    "            current = current.next\n",
    "        \n",
    "        cur = count - n\n",
    "        current = dummy\n",
    "        while cur:\n",
    "            current = current.next\n",
    "            cur -= 1\n",
    "        current.next = current.next.next\n",
    "\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9110e43",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 法二：双指针法\n",
    "class Solution:\n",
    "    def removeNthFromEnd(self,head:ListNode,n:int) -> ListNode:\n",
    "        dummy_head = ListNode(0,head)\n",
    "        fast = slow = dummy_head\n",
    "\n",
    "        for _ in range(n+1):\n",
    "            if fast:\n",
    "                fast = fast.next\n",
    "\n",
    "        while fast:\n",
    "            slow = slow.next\n",
    "            fast = fast.next\n",
    "\n",
    "        slow.next = slow.next.next\n",
    "\n",
    "        return dummy_head.next\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env_py38",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
